<template>
  <v-dialog
    v-model="dialogFormVisible"
    :persistent="true"
    max-width="800px"
    @click:outside="close"
  >
    <v-card>
      <v-card-title>{{ title }}</v-card-title>
      
      <v-card-text>
        <v-form ref="form" v-model="formValid">
          <v-row>
            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.roleCode"
                label="角色编号"
                :rules="rules.roleCode"
                      :disabled="!formStatus"
                variant="outlined"
                density="compact"
                hide-details="auto"
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field
                v-model="form.roleName"
                label="角色名称"
                :rules="rules.roleName"
                variant="outlined"
                density="compact"
                hide-details="auto"
              ></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-select
                v-model="form.dataScope"
                label="数据范围"
                :items="$getDictList('role_data_scope')"
                item-title="dictName"
                item-value="dictValue"
                variant="outlined"
                density="compact"
                hide-details="auto"
              ></v-select>
            </v-col>

            <v-col cols="12" md="6">
              <v-textarea
                v-model="form.remark"
                label="备注"
                variant="outlined"
                density="compact"
                hide-details="auto"
                rows="3"
              ></v-textarea>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
          color="grey-darken-1"
          variant="text"
          @click="close"
        >
          取消
        </v-btn>
        <v-btn
          color="primary"
          variant="text"
          @click="save"
        >
          确定
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
  import { doInsert, doUpdate } from "@/api/system/role/roleManagement";
import { isNull } from "@/utils/validate";
  import { validatorRule } from "@/utils/validateRule";
  import { getUserInfo } from "@/api/user";
  import { useMessage } from "@/composables/useMessage";

  export default {
    name: "RoleManagementEdit",
    setup() {
      const { success: showSuccess } = useMessage();
      return {
        showSuccess
      };
    },
    data() {
      return {
      formValid: false,
        formStatus: true,
        userInfo: null,
        form: {
          label: "",
        tenantId: "",
          izLock: '0',
          dataScope: '0',
          version: 0
        },
        rules: {
          roleCode: [
          v => !!v || '请输入编号',
          v => !v || validatorRule.IS_GENERAL(v) || '编号格式不正确'
          ],
          roleName: [
          v => !!v || '请输入名称',
          v => !v || validatorRule.IS_GENERAL_WITH_CHINESE(v) || '名称格式不正确'
        ]
        },
        title: "",
        dialogFormVisible: false,
      };
    },
    async created() {
      // 预加载字典数据
      await this.preloadDictionaries();
      this.getUser();
    },
    methods: {
      /**
       * 预加载字典数据
       */
      async preloadDictionaries() {
        try {
          // 预加载需要的字典
          const dictTypes = ['role_data_scope'];
          const promises = dictTypes.map(typeCode => this.$getDictListAsync(typeCode));
          await Promise.all(promises);
          console.log('编辑组件字典数据预加载完成');
        } catch (error) {
          console.error('编辑组件字典数据预加载失败:', error);
        }
      },

      showEdit(row, activeName) {
        if (!row) {
          this.title = "添加";
        } else {
          this.title = "编辑";
          this.formStatus = false;
          this.form = Object.assign({}, row);
        }
        this.form.label = activeName;
        this.dialogFormVisible = true;
      },
      close() {
        this.dialogFormVisible = false;
        this.formStatus = true;
      this.$refs.form.reset();
        this.form = this.$options.data().form;
      },
    async save() {
      const { valid } = await this.$refs.form.validate();
      
          if (valid) {
        try {
            if (!isNull(this.form.id)) {
              const response = await doUpdate(this.form);
              this.showSuccess(response.data?.msg || "更新成功");
            } else {
              const response = await doInsert(this.form);
              this.showSuccess(response.data?.msg || "添加成功");
            }
            await this.$emit("fetchData");
            this.close();
        } catch (error) {
          console.error(error);
        }
          }
      },
      async getUser() {
      try {
        const { data } = await getUserInfo();
        if (!isNull(data)) {
          this.userInfo = Object.assign({}, data);
        }
      } catch (error) {
        console.error(error);
        }
    }
  }
  };
</script>
